﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using System;
using System.Collections.Generic;

namespace Blueprints.IO
{
    /// <summary>
    /// A set of extensions for an IBlueprintReader.
    /// </summary>
    internal static class IBlueprintReaderExtensions
    {
        private static bool MoveToContent(this IEnumerator<INode> reader)
        {
            try
            {
                if (reader.Current == null)
                {
                    if (!reader.MoveNext())
                    {
                        return false;
                    }
                }
            }
            catch
            {
                /*
                 * Calling a deserialize overload with a Stream or Uri, the reader is
                 * already at the first element. However when an overload is used to
                 * which an IBlueprintReader is supplied, there is no way to tell whether 
                 * MoveNext() has been called. Calling MoveNext() unconditionally is not
                 * an option, as it may then skip the root node.
                 * The behavior of IEnumerator<>.Current is documented as "undefined";
                 * some return null, others throw.
                 */
                if (!reader.MoveNext())
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Attempts to read to a start node with an id matching <paramref name="id"/>.
        /// </summary>
        /// <param name="reader">The blueprint reader to read from.</param>
        /// <param name="id">The id to find.</param>
        /// <returns>True if a matching node was found, false otherwise.</returns>
        public static bool MoveToId(this IEnumerator<INode> reader, string id)
        {
            if (!MoveToContent(reader))
            {
                return false;
            }

            do
            {
                if (reader.Current.NodeType != NodeType.StartNode)
                {
                    continue;
                }

                if (!id.Equals(reader.Current.Id, StringComparison.Ordinal))
                {
                    continue;
                }

                return true;
            }
            while (reader.MoveNext());
            return false;
        }

        /// <summary>
        /// Attempts to read to a start node.
        /// </summary>
        /// <param name="reader">The blueprint reader to read from.</param>
        /// <returns>True if a start node was found, false otherwise.</returns>
        public static bool MoveToStartNode(this IEnumerator<INode> reader)
        {
            if (!MoveToContent(reader))
            {
                return false;
            }

            do
            {
                if (reader.Current.NodeType == NodeType.StartNode)
                {
                    return true;
                }
            }
            while (reader.MoveNext());
            return false;
        }

        /// <summary>
        /// Attempts to read to an end node.
        /// </summary>
        /// <param name="reader">The blueprint reader to read from.</param>
        public static void MoveToEndNode(this NodeInfoReader reader)
        {
            NodeInfo current = reader.Current;
            if (current.Node == null)
            {
                throw new BlueprintException("Cannot read to an end node if the reader is not currently on a start node");
            }

            if (current.Node.NodeType != NodeType.StartNode)
            {
                throw new BlueprintDocumentException("Cannot read to an end node if the reader is not currently on a start node", current.Path);
            }
            
            int depth = 1;
            while (reader.MoveNext())
            {
                switch (reader.Current.Node.NodeType)
                {
                    case NodeType.StartNode:
                        depth++;
                        break;
                    case NodeType.EndNode:
                        depth--;
                        if (depth == 0)
                        {
                            return;
                        }

                        break;
                }
            }

            throw new BlueprintDocumentException("No matching end node found", current.Path);
        }

        /// <summary>
        /// Reads all start nodes that are descendants of the current node. 
        /// </summary>
        /// <param name="reader">The blueprint reader to read from.</param>
        /// <returns>All start nodes that are descendants of the current node. </returns>
        public static IEnumerable<INode> ReadSubNodes(this NodeInfoReader reader)
        {
            NodeInfo current = reader.Current;
            if (current.Node == null)
            {
                throw new BlueprintException("Cannot read sub nodes if the reader is not currently on a start node");
            }

            if (current.Node.NodeType != NodeType.StartNode)
            {
                throw new BlueprintDocumentException("Cannot read sub nodes if the reader is not currently on a start node", current.Path);
            }

            while (reader.MoveNext())
            {
                INode subNode = reader.Current.Node;
                switch (subNode.NodeType)
                {
                    case NodeType.StartNode:
                        yield return subNode;
                        break;
                    case NodeType.EndNode:
                        yield break;
                }
            }
        }
        
        /// <summary>
        /// Attempts to read the content as a child of the current node, and advances the reader to the end node.
        /// </summary>
        /// <param name="reader">The reader to read from.</param>
        /// <returns>The read content.</returns>
        public static string ReadContent(this NodeInfoReader reader)
        {
            NodeInfo current = reader.Current;
            if (current.Node == null)
            {
                throw new BlueprintException("Cannot read contents if the reader is not currently on a start node");
            }

            if (current.Node.NodeType != NodeType.StartNode)
            {
                throw new BlueprintDocumentException("Cannot read contents if the reader is not currently on a start node", current.Path);
            }

            List<string> content = new List<string>();
            int depth = 1;
            while (reader.MoveNext())
            {
                INode child = reader.Current.Node;
                switch (child.NodeType)
                {
                    case NodeType.StartNode:
                        depth++;
                        break;
                    case NodeType.Content:
                        if (depth == 1)
                        {
                            content.Add(child.Content);
                        }

                        break;
                    case NodeType.EndNode:
                        depth--;
                        if (depth == 0)
                        {
                            return string.Join(" ", content.ToArray());
                        }

                        break;
                }
            }

            throw new BlueprintDocumentException("No matching end node found", current.Path);
        }
    }
}